# -*- coding: utf-8 -*-
'''
Created on 08-10-2012

@author: LONG HOANG GIANG
'''

import sqlite3 as db
import traceback

class SQLiteHelper():
    
    _conn = None
    _cursor = None
    
    def __init__(self, database):
        self._conn = db.connect(database)
        self._cursor = self._conn.cursor()
    
    def getConnection(self):
        return self._conn
    
    def getCursor(self):
        return self._cursor
    
    def execute(self, sql):
        if self._cursor is None: return
        self._cursor.execute(sql)
        return self._cursor.lastrowid
    
    def fetchAll(self, sql):
        if self._cursor is None: return None
        rows = None
        try:
            self._cursor.execute(sql)
            rows = self._cursor.fetchall()
        except:
            traceback.print_exc()
        return rows
    
    def fetchOne(self, sql):
        if self._cursor == None: return None
        row = None
        try:
            self._cursor.execute(sql)
            row = self._cursor.fetchone()
        except:
            traceback.print_exc()
        return row
    
    def lastrowid(self):
        if self._cursor == None: return -1
        return self._cursor.lastrowid
    
    def commit(self):
        if self._conn is not None:
            self._conn.commit()
    
    def close(self):
        try:
            if self._cursor is not None:
                self._cursor.close()
            if self._conn is not None:
                self._conn.close()
        except:
            traceback.extract_stack()
        return
        
    def __del__(self):
        self.close()
    